/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SearchPatient.java
 *
 * Created on Apr 27, 2011, 12:30:20 PM
 */
package khmhappointmentsystem;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.JSpinner;
import javax.swing.JSpinner.DateEditor;
import javax.swing.SpinnerDateModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.DateFormatter;
import javax.swing.text.DefaultFormatterFactory;
import org.jdesktop.application.Action;

/**
 *
 * @author mbelisle
 */
public class FrmNewAppointment extends javax.swing.JInternalFrame {

    static final Logger logger = Logger.getLogger(FrmNewAppointment.class.getName());
    ArrayList<String> firstName = new ArrayList<String>();
    ArrayList<String> lastName = new ArrayList<String>();
    ArrayList<String> id = new ArrayList<String>();
    ArrayList<String> dob = new ArrayList<String>();
    String warnings = "";

    /** Creates new form SearchPatient */
    public FrmNewAppointment() {
        initComponents();
        loadComboValues();
        loadSpecialist();
        setCalendarDate();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cmdclose = new javax.swing.JButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        txtSearch = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        cmdsearch = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblSearch = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtssn = new javax.swing.JTextField();
        txtFtName = new javax.swing.JTextField();
        txtLtName = new javax.swing.JTextField();
        cmdAppointment = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        lblClinic = new javax.swing.JLabel();
        cmbClinic = new javax.swing.JComboBox();
        jLabel10 = new javax.swing.JLabel();
        cmbSpecialist = new javax.swing.JComboBox();
        jLabel12 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        Calendar calendar = new GregorianCalendar();
        calendar.set(Calendar.HOUR, 13); // 1pm
        SpinnerDateModel dateModel = new SpinnerDateModel(calendar.getTime(), null,null, Calendar.HOUR);
        spinner = new JSpinner(dateModel);
        calDate = new com.toedter.calendar.JDateChooser();
        jLabel5 = new javax.swing.JLabel();
        chkNewPatient = new javax.swing.JCheckBox();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(FrmNewAppointment.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setFrameIcon(resourceMap.getIcon("Form.frameIcon")); // NOI18N
        setName("Form"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance().getContext().getActionMap(FrmNewAppointment.class, this);
        cmdclose.setAction(actionMap.get("close")); // NOI18N
        cmdclose.setIcon(resourceMap.getIcon("cmdclose.icon")); // NOI18N
        cmdclose.setText(resourceMap.getString("cmdclose.text")); // NOI18N
        cmdclose.setName("cmdclose"); // NOI18N

        jTabbedPane1.setName("jTabbedPane1"); // NOI18N

        jPanel2.setName("jPanel2"); // NOI18N

        txtSearch.setText(resourceMap.getString("txtSearch.text")); // NOI18N
        txtSearch.setName("txtSearch"); // NOI18N

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        cmdsearch.setAction(actionMap.get("Search")); // NOI18N
        cmdsearch.setIcon(resourceMap.getIcon("cmdsearch.icon")); // NOI18N
        cmdsearch.setText(resourceMap.getString("cmdsearch.text")); // NOI18N
        cmdsearch.setName("cmdsearch"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tblSearch.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "First Name", "Last Name"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblSearch.setName("tblSearch"); // NOI18N
        tblSearch.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblSearchMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblSearch);
        tblSearch.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("tblSearch.columnModel.title0")); // NOI18N
        tblSearch.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("tblSearch.columnModel.title1")); // NOI18N
        tblSearch.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("tblSearch.columnModel.title2")); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 384, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtSearch, javax.swing.GroupLayout.DEFAULT_SIZE, 178, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cmdsearch, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmdsearch))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane1.addTab(resourceMap.getString("jPanel2.TabConstraints.tabTitle"), jPanel2); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        txtssn.setEditable(false);
        txtssn.setText(resourceMap.getString("txtssn.text")); // NOI18N
        txtssn.setName("txtssn"); // NOI18N

        txtFtName.setEditable(false);
        txtFtName.setText(resourceMap.getString("txtFtName.text")); // NOI18N
        txtFtName.setName("txtFtName"); // NOI18N

        txtLtName.setEditable(false);
        txtLtName.setText(resourceMap.getString("txtLtName.text")); // NOI18N
        txtLtName.setName("txtLtName"); // NOI18N

        cmdAppointment.setAction(actionMap.get("bookAppointment")); // NOI18N
        cmdAppointment.setText(resourceMap.getString("cmdAppointment.text")); // NOI18N
        cmdAppointment.setName("cmdAppointment"); // NOI18N

        jLabel9.setFont(resourceMap.getFont("jLabel9.font")); // NOI18N
        jLabel9.setText(resourceMap.getString("jLabel9.text")); // NOI18N
        jLabel9.setName("jLabel9"); // NOI18N

        jPanel4.setName("jPanel4"); // NOI18N

        lblClinic.setText(resourceMap.getString("lblClinic.text")); // NOI18N
        lblClinic.setName("lblClinic"); // NOI18N

        cmbClinic.setName("cmbClinic"); // NOI18N

        jLabel10.setText(resourceMap.getString("jLabel10.text")); // NOI18N
        jLabel10.setName("jLabel10"); // NOI18N

        cmbSpecialist.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbSpecialist.setName("cmbSpecialist"); // NOI18N

        jLabel12.setText(resourceMap.getString("jLabel12.text")); // NOI18N
        jLabel12.setName("jLabel12"); // NOI18N

        jLabel11.setText(resourceMap.getString("jLabel11.text")); // NOI18N
        jLabel11.setName("jLabel11"); // NOI18N

        spinner.setName("spinner"); // NOI18N

        calDate.setName("calDate"); // NOI18N

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabel11)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 244, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(lblClinic)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cmbClinic, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel10)
                            .addComponent(jLabel12))
                        .addGap(16, 16, 16)
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(spinner, javax.swing.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE)
                            .addComponent(calDate, javax.swing.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE)
                            .addComponent(cmbSpecialist, 0, 186, Short.MAX_VALUE))))
                .addGap(103, 103, 103))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblClinic)
                    .addComponent(cmbClinic, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(17, 17, 17)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbSpecialist, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10))
                .addGap(18, 18, 18)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel11)
                    .addComponent(calDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(spinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        JFormattedTextField tf = ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField();
        DefaultFormatterFactory factory = (DefaultFormatterFactory) tf.getFormatterFactory();
        DateFormatter formatter = (DateFormatter) factory.getDefaultFormatter();
        spinner.setEditor(new DateEditor(spinner, "hh:mm a"));
        // Change the date format to only show the hours
        formatter.setFormat(new SimpleDateFormat("hh:mm a"));
        //formatter.setFormat(new JSpinner.DateEditor(spinner, "hh:mm a"));// SimpleDateFormat("hh:mm a"));
    //formatter.setFormat(new SimpleDateFormat("HH:00 a"));

    jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
    jLabel5.setName("jLabel5"); // NOI18N

    chkNewPatient.setText(resourceMap.getString("chkNewPatient.text")); // NOI18N
    chkNewPatient.setName("chkNewPatient"); // NOI18N

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel4)
                    .addGap(36, 36, 36)
                    .addComponent(txtssn, javax.swing.GroupLayout.DEFAULT_SIZE, 333, Short.MAX_VALUE))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(jLabel2)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(txtFtName, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(jLabel3)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(txtLtName, javax.swing.GroupLayout.DEFAULT_SIZE, 326, Short.MAX_VALUE))))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(117, 117, 117)
                    .addComponent(jLabel9))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 4, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(chkNewPatient)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 166, Short.MAX_VALUE)
                            .addComponent(cmdAppointment)))))
            .addContainerGap())
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel4)
                .addComponent(txtssn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel2)
                .addComponent(txtFtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel3)
                .addComponent(txtLtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jLabel9)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jLabel5)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(chkNewPatient)
                .addComponent(cmdAppointment))
            .addGap(47, 47, 47))
    );

    jTabbedPane1.addTab(resourceMap.getString("jPanel1.TabConstraints.tabTitle"), jPanel1); // NOI18N

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(cmdclose, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 409, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addContainerGap(19, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 387, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(cmdclose)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    setBounds((screenSize.width-448)/2, (screenSize.height-480)/2, 448, 480);
    }// </editor-fold>//GEN-END:initComponents

    private void tblSearchMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_tblSearchMouseClicked
    {//GEN-HEADEREND:event_tblSearchMouseClicked

        String id_no = tblSearch.getValueAt(tblSearch.getSelectedRow(), 0).toString();
        loadPatientInfo(id_no);
        jTabbedPane1.setSelectedIndex(jTabbedPane1.getSelectedIndex() + 1);
}//GEN-LAST:event_tblSearchMouseClicked

    private void loadPatientInfo(String selected_id) {
        for (int i = 0; i < id.size(); i++) {
            String pt_ssn = id.get(i);
            if (selected_id.equals(pt_ssn)) {
                txtssn.setText(pt_ssn);
                txtFtName.setText(firstName.get(i));
                txtLtName.setText(lastName.get(i));
            }
        }
    }

    @Action
    public void close() {
        this.dispose();
    }

    @Action
    public void Search() {

        try {

            firstName = new ArrayList<String>();
            lastName = new ArrayList<String>();
            id = new ArrayList<String>();
            dob = new ArrayList<String>();

            String query = "SELECT pt_id, pt_ftname, pt_ltname, pt_DOB FROM Patient_Info WHERE (pt_ftname LIKE ? OR pt_ltname LIKE ?) ORDER BY pt_id, pt_ftname, pt_ltname, pt_DOB";
            PreparedStatement pstmt = Environment.getDbConn().prepareStatement(query);
            pstmt.setString(1, Utilities.percent(txtSearch.getText().trim()));
            pstmt.setString(2, Utilities.percent(txtSearch.getText().trim()));

            ResultSet rs = pstmt.executeQuery();

            while (rs.next()) {
                id.add(rs.getString("pt_id"));
                firstName.add(rs.getString("pt_ftname"));
                lastName.add(rs.getString("pt_ltname"));
                dob.add(Utilities.MDY_Formatter.format(rs.getDate("pt_DOB")));
            }

            if (firstName.isEmpty() == false)//If there were results in the query create a table model with the vectors.
            {
                DefaultTableModel model = new DefaultTableModel() {

                    @Override
                    public Class getColumnClass(int columnIndex) {
                        Object o = getValueAt(0, columnIndex);
                        if (o == null) {
                            return Object.class;
                        } else {
                            return o.getClass();
                        }
                    }
                };

                model.addColumn("ID", id.toArray());
                model.addColumn("First Name", firstName.toArray());
                model.addColumn("Last Name", lastName.toArray());
                model.addColumn("Date of Birth", dob.toArray());
                tblSearch.setModel(model);
            } else //If the query returned no results create a table model that displays a "No Result" message and disables the view salaries register button.
            {
                DefaultTableModel model = new DefaultTableModel() {

                    @Override
                    public boolean isCellEditable(int row, int column) {
                        return false;
                    }

                    @Override
                    public Class getColumnClass(int columnIndex) {
                        Object o = getValueAt(0, columnIndex);
                        if (o == null) {
                            return Object.class;
                        } else {
                            return o.getClass();
                        }
                    }
                };

                id.add("No Results");
                firstName.add("No Results");
                lastName.add("No Results");
                dob.add("No Results");

                model.addColumn("ID", id.toArray());
                model.addColumn("First Name", firstName.toArray());
                model.addColumn("Last Name", lastName.toArray());
                model.addColumn("Date of Birth", dob.toArray());
                tblSearch.setModel(model);
            }
        } catch (Exception e) {
            String message = "An error occurred while searching for the patients.";
            logger.log(Level.SEVERE, message, e);
        }
    }

    private void loadComboValues() {
        cmbClinic.removeAllItems();
        cmbClinic.addItem(" ");
        String query = "SELECT DISTINCT name FROM clinic ORDER BY name";
        try {
            PreparedStatement prep = Environment.getDbConn().prepareStatement(query);
            ResultSet rs = prep.executeQuery();

            while (rs.next()) {
                cmbClinic.addItem(rs.getString(1));
            }
            rs.close();
            prep.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void loadSpecialist() {
        cmbSpecialist.removeAllItems();
        cmbSpecialist.addItem(" ");
        String query = "SELECT DISTINCT specialist FROM clinic ORDER BY specialist";
        try {
            PreparedStatement prep = Environment.getDbConn().prepareStatement(query);
            ResultSet rs = prep.executeQuery();

            while (rs.next()) {
                cmbSpecialist.addItem(rs.getString(1));
            }
            rs.close();
            prep.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void setCalendarDate() {
        calDate.setDate(new java.util.Date());
    }

    @Action
    public void bookAppointment() {

        if (!passedValidation()) {
            Utilities.showWarningMessage(rootPane, warnings);
            return;
        }

        //create object for date
        DateFormat MDY_Formatter = new SimpleDateFormat("MM-dd-yyyy");
        DateFormat Time_Formatter = new SimpleDateFormat("hh:mm a");
        String date = MDY_Formatter.format(calDate.getDate());
        String pt_id = txtssn.getText();
        String clinic = cmbClinic.getSelectedItem().toString();
        String specialist = cmbSpecialist.getSelectedItem().toString();
        String time = Time_Formatter.format(spinner.getValue());
        String check = "y";
        String message = "";


        if (chkNewPatient.isSelected()) {
            try {
                String query = "INSERT INTO Appointments ("
                        + "pt_id,"
                        + "clinic,"
                        + "specialist,"
                        + "date,"
                        + "time,"
                        + "new_patient)"
                        + "Values(?,?,?,?,?,?)";

                PreparedStatement stmt = Environment.getDbConn().prepareStatement(query);
                stmt.setString(1, pt_id);
                stmt.setString(2, clinic);
                stmt.setString(3, specialist);
                stmt.setString(4, date);
                stmt.setString(5, time);
                stmt.setString(6, check);

                stmt.executeUpdate();
                JOptionPane.showMessageDialog(rootPane, "New Appointment booked successfully.");
                chkNewPatient.setSelected(false);
            } catch (Exception e) {
                System.out.println("Error occured while booking patient appointment.");
                e.printStackTrace();
            }
        } else {
            try {
                String query = "INSERT INTO Appointments ("
                        + "pt_id,"
                        + "clinic,"
                        + "specialist,"
                        + "date,"
                        + "time)"
                        + "Values(?,?,?,?,?)";

                PreparedStatement stmt = Environment.getDbConn().prepareStatement(query);
                stmt.setString(1, pt_id);
                stmt.setString(2, clinic);
                stmt.setString(3, specialist);
                stmt.setString(4, date);
                stmt.setString(5, time);

                stmt.executeUpdate();
                JOptionPane.showMessageDialog(rootPane, "New Appointment booked successfully.");
            } catch (Exception e) {
                Utilities.showErrorMessage(rootPane, message);
                message = "Error occured while booking patient appointment.";
                e.printStackTrace();
            }
        }

        txtssn.setText("");
        txtFtName.setText("");
        txtLtName.setText("");
    }

    private boolean passedValidation() {
        boolean passed = true;
        warnings = "";
        //create object for date
        DateFormat MDY_Formatter = new SimpleDateFormat("MM-dd-yyyy");
        DateFormat Time_Formatter = new SimpleDateFormat("hh:mm a");
        String date = MDY_Formatter.format(calDate.getDate());
        String time = Time_Formatter.format(spinner.getValue());
        String name = cmbClinic.getSelectedItem().toString();
        String specialist = cmbSpecialist.getSelectedItem().toString();
        String clinicID = Clinic.getClinicID(name, specialist);

        if (Clinic.totalVisitors(specialist, date) < Clinic.maxVisitors(clinicID)) {
            passed = true;
        }
        
        if (Clinic.totalVisitors(specialist, date) > Clinic.maxVisitors(clinicID)) {
            warnings += "The clinic has reached is maximun allowed visitors. Please try another date.";
            passed = false;
        }
        return passed;

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private com.toedter.calendar.JDateChooser calDate;
    private javax.swing.JCheckBox chkNewPatient;
    private javax.swing.JComboBox cmbClinic;
    private javax.swing.JComboBox cmbSpecialist;
    private javax.swing.JButton cmdAppointment;
    private javax.swing.JButton cmdclose;
    private javax.swing.JButton cmdsearch;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JLabel lblClinic;
    private javax.swing.JSpinner spinner;
    private javax.swing.JTable tblSearch;
    private javax.swing.JTextField txtFtName;
    private javax.swing.JTextField txtLtName;
    private javax.swing.JTextField txtSearch;
    private javax.swing.JTextField txtssn;
    // End of variables declaration//GEN-END:variables
}
